package com.corn.config;

import com.corn.security.MyAccessDeniedHandler;
import com.corn.security.RedisTokenRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

/**
 * @author : Jim Wu
 * @version 1.0
 * @function :
 * @since : 2021/4/8 11:49
 */

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


    /**
     * 密码解密器
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置一个内存的用户
     *
     * @param auth
     * @throws Exception
     */
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        String password = passwordEncoder().encode("123");
//        auth.inMemoryAuthentication().withUser("root").password(password).authorities("add","delete","select").roles("admin");
//    }

    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 使用UserDetailService来查询用户信息
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Autowired
    private MyAccessDeniedHandler accessDeniedHandler;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Bean
    public PersistentTokenRepository persistentTokenRepository(RedisTemplate<String, Object> redisTemplate) {
        return new RedisTokenRepository(redisTemplate);
    }

    private final String SECURITY_KEY = "123456";

    @Bean
    public RememberMeServices rememberMeServices() {
        return new PersistentTokenBasedRememberMeServices(SECURITY_KEY, userDetailsService, persistentTokenRepository(redisTemplate));
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() // 关闭csrf验证
                .formLogin().loginPage("/html/login") // 自定义登录页面
                .defaultSuccessUrl("/html/index") // 默认登录成功跳转
                .loginProcessingUrl("/user/login") // 登录处理器controller POST请求地址
                .permitAll() // 放行
                .and()
                .logout().logoutUrl("/user/logout") // 登出地址
                .logoutSuccessUrl("/html/login") // 登出跳转URL
                .permitAll()
                .and()
                .authorizeRequests()
                .antMatchers("/", "/hello").permitAll() // / 和 /hello 放行 建议可以放在配置文件中
                .anyRequest().authenticated()// 其他所有请求必须认证
                .and()
                .exceptionHandling().accessDeniedHandler(accessDeniedHandler) // 异常处理

                .and().rememberMe().rememberMeServices(rememberMeServices()); // 记住我 服务
    }
}
